package com.javakc.pms.order.dispord.service;

import com.javakc.commonutils.jpa.base.service.BaseService;
import com.javakc.commonutils.jpa.dynamic.SimpleSpecificationBuilder;
import com.javakc.pms.order.dispord.dao.DispOrdDao;
import com.javakc.pms.order.dispord.entity.DispOrd;
import com.javakc.pms.order.dispord.vo.DispOrdQuery;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class DispOrdService extends BaseService<DispOrdDao, DispOrd> {


    /**
     * 调度指令库  查询所有数据
     * @return 实例类
     */
    public List<DispOrd> queryAll() {
        return dao.findAll();
    }
    /**
     * 查询指令名称是否重复
     * @param dispOrd 实体类
     * @return 0 or 1
     */
    public int queryBYName(DispOrd dispOrd){
        int count = dao.queryByName(dispOrd.getOrderName());
        return count;
    }

    /**
     * 调度指令库  分页带条件查询
     * @param pageNo  页码
     * @param pageSize  当前页最大条数
     * @param dispOrdQuery   封装长训条件
     * @return   分页对象
     */
    public Page<DispOrd> queryByPage(Integer pageNo, Integer pageSize, DispOrdQuery dispOrdQuery){
        SimpleSpecificationBuilder ssb=new SimpleSpecificationBuilder();
        if(!ObjectUtils.isEmpty(dispOrdQuery) && !ObjectUtils.isEmpty(dispOrdQuery.getOrderName())&& !dispOrdQuery.getOrderName().trim().equals("")){
            ssb.and("orderName",":",dispOrdQuery.getOrderName().trim());
        }

        Page<DispOrd> page= dao.findAll(ssb.getSpecification(),PageRequest.of(pageNo-1,pageSize));
        return page;
    }

    /**
     * 调度指令库   新增一条数据
     * @param dispOrd 实体类
     */
    @Transactional
    public void save(DispOrd dispOrd){
        int count = this.queryBYName(dispOrd);
        if (!ObjectUtils.isEmpty(dispOrd) && count == 0){
            dao.save(dispOrd);
        }
    }


    /**
     * 调度指令库  带id修改一条数据
     * @param dispOrd 实体类
     */
    @Transactional
    public void update(DispOrd dispOrd){
        if (!ObjectUtils.isEmpty(dispOrd)){
          dao.save(dispOrd);
        }
    }

    /**
     * 导出Excel表格
     * @param response 返回响应
     */
    public void exportExcel(HttpServletResponse response){
        //设置表头
        String titles[] ={"优先级","专业类型","指令名称","指令描述"};
        //创建工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();
        //创建sheet
        HSSFSheet sheet = workbook.createSheet();
        //创建第一行，设置表头
        HSSFRow row = sheet.createRow(0);
        //循环String数组取出表头
        for (int i = 0; i < titles.length; i++) {
             row.createCell(i).setCellValue(i);
        }
        //查询所有数据
        List<DispOrd> dispOrdList = dao.findAll();
        if (null != dispOrdList){
            for (int i = 0; i < dispOrdList.size(); i++) {
                DispOrd dispOrd = dispOrdList.get(i);
                //创建从第二行开始的所有行
                HSSFRow hssfRow = sheet.createRow(i + 1);
                //设置第二行内容
                hssfRow.createCell(0).setCellValue(dispOrd.getPriority());
                //设置第三行内容
                hssfRow.createCell(1).setCellValue(dispOrd.getOrderType());
                //设置第四行内容
                hssfRow.createCell(2).setCellValue(dispOrd.getOrderName());
                //设置第五行内容
                hssfRow.createCell(3).setCellValue(dispOrd.getOrderDescribe());
            }
        }
        //设置响应信息，返回
        String fileName = new String(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        try {
            // ## 6.将Excel文件输出到客户端浏览器
            response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");
            ServletOutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导入Excel文件
     * @param file 传入的文件
     */
    @Transactional
    public void importExcel(MultipartFile file){
        //得到数据
        try {
            //得到文件流
            InputStream inputStream = file.getInputStream();
            //创建一个接口
            Workbook workbook = null;
            /**
             * 判断不同的后缀格式
             */
            if (file.getOriginalFilename().endsWith(".xlsx")){
                workbook = new XSSFWorkbook(inputStream);
            }else {
                workbook = new HSSFWorkbook(inputStream);
            }
            //获取sheet的个数
            int numberOfSheets = workbook.getNumberOfSheets();
            //循环
            for (int i = 0; i < numberOfSheets; i++) {
                //创建DispOrd 集合
                List<DispOrd> list = new ArrayList<>();
                //得到对应的某一个sheet
                Sheet sheet = workbook.getSheetAt(i);
                //获取行
                int physicalNumberOfRows = sheet.getPhysicalNumberOfRows();
                //循环获取全部的行
                for (int j = 1; j < physicalNumberOfRows; j++) {
                    //获取行内的具体内容
                    Row cells = sheet.getRow(j);
                    //把行内的内容放入封装类中
                    DispOrd dispOrd = new DispOrd();
                    dispOrd.setPriority((int)cells.getCell(0).getNumericCellValue());
                    dispOrd.setOrderType((int)cells.getCell(1).getNumericCellValue());
                    dispOrd.setOrderName(cells.getCell(2).getStringCellValue());
                    dispOrd.setOrderDescribe(cells.getCell(3).getStringCellValue());
                    list.add(dispOrd);
                }
                //保存
                dao.saveAll(list);

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



}
